import React, {Component} from 'react';
import {View, SafeAreaView, TouchableOpacity, Text, Share} from 'react-native';
import {WebView} from 'react-native-webview';

const html = `
  <html>
    <head></head>
    <body>
      <h1>这是H5页面</h1>
      <button onclick="sayHelloToApp()">sayHelloToApp</button>
      <script>
        window.onLogin = (data) => {
          alert(JSON.stringify(data))
        }
        function sayHelloToApp(){
          let data = {
            action: 'login',
            callback: 'onLogin',
            params: {
              msg:'从H5页面发来的消息'
            }
          };
          window.ReactNativeWebView.postMessage(JSON.stringify(data));
        }
      </script>
    </body>
  </html>
`;

/**
 * APP端注入JS脚本到H5端，供H5页面调用。
 * @type {string}
 */
const H5AppBridge = `
  window.H5AppBridge = {
    sayHello:function(data){
      let objData = {};
      // 声明事件类型。
      objData.type='sayHello';
      objData.data = data;
      // 这里注意要把data转化为JSON字符串，postMessage()只接受字符串参数。
      window.ReactNativeWebView.postMessage(JSON.stringify(objData));
    }
  };
`;

export default class WebviewH5 extends Component {
  constructor(props) {
    super(props);
  }
  render() {
    const runFirst = `
      window.MICRO_TASK = true;
      true; // note: this is required, or you'll sometimes get silent failures
    `;
    return (
      <SafeAreaView style={{flex: 1, paddingTop: 50}}>
        <TouchableOpacity
          style={{
            height: 40,
            borderRadius: 20,
            paddingLeft: 15,
            paddingRight: 15,
            justifyContent: 'center',
            alignItems: 'center',
            backgroundColor: '#2988ff',
          }}>
          <Text>sayHello</Text>
        </TouchableOpacity>
        <WebView
          ref={'webview_ref'}
          source={{html: html}}
          injectedJavaScriptBeforeContentLoaded={runFirst}
          domStorageEnabled={true}
          scrollEnabled={true}
          javaScriptEnabled={true}
          showsVerticalScrollIndicator={false}
          showsHorizontalScrollIndicator={false}
          onMessage={(event) => {
            this.handleMessage(event);
          }}
        />
      </SafeAreaView>
    );
  }

  /**
   * 在h5中执行JS代码
   * @param {*} jsCode
   */
  injectJavaScript = (jsCode) => {
    const webView = this.refs['webview_ref'];
    webView.injectJavaScript(jsCode);
  };

  /**
   * 监听来自h5的消息
   * @param {*} event
   */
  handleMessage = (event) => {
    const {navigation} = this.props;
    const message = event.nativeEvent;
    try {
      const payload = JSON.parse(message.data);
      switch (payload.action) {
        /**
         * 登录
         */
        case 'login':
          let params = payload.params;
          let callback = payload.callback;
          if (params) {
            navigation.navigate('Login', {
              success: (userInfo) => {
                let jsCode = `window.${callback} && window.${callback}(${JSON.stringify(
                  userInfo,
                )});`;
                this.injectJavaScript(jsCode);
              },
            });
          }
          break;
        case 'share':
          alert('share');
      }
    } catch (e) {
      alert('调用APP方法参数错误！参数为：' + message.data);
    }
  };
}
